<?php

namespace app\admin\model\test;

use think\Model;


class Test extends Model
{

    // 表名
    protected $name = 'test';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'status_text',
        'limittime_text'
    ];
    

    
    public function getStatusList()
    {
        return ['0' => __('Status 0'), '1' => __('Status 1')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getLimittimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['limittime']) ? $data['limittime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setLimittimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    public static function getTestDetail($id,$answer = false)
    {
		$info = self::where(['id'=>$id])->find()->toArray();
		//获取试题
		$testitemList = collection(Testitem::where(['test_id'=>$id])->with('itembank')->select())->toArray();
		if(!$answer){
			foreach($testitemList as $key=>$val){
				$values = json_decode($val['itembank']['values'],true);
				//删除答案
				if(is_array($values)){
					foreach($values as $kk=>$vv){
						if(isset($values[$kk]['answer'])){
							unset($values[$kk]['answer']);
						}
					}
				}
				$testitemList[$key]['itembank']['values'] = $values;
				unset($testitemList[$key]['itembank']['answer']);
				unset($testitemList[$key]['itembank']['answer_key']);
			}
		}
		$info['itemList'] = $testitemList;
		return $info;
    }


    public function article()
    {
        return $this->belongsTo('app\admin\model\article\Article', 'article_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function merchant()
    {
        return $this->belongsTo('app\admin\model\Merchant', 'merchant_id', 'merchant_id', [], 'LEFT')->setEagerlyType(0);
    }
}
